package com.example.zbh.dsliao.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.example.zbh.dsliao.ui.activty.DownLoaderActivity;
import com.example.zbh.dsliao.ui.adapter.DownLoadAdapter;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.net.DownloadListener;
import com.example.zbh.dsliao.utils.net.Downloader;

import java.io.File;

/**
 * Created by yaolin on 15/11/30.
 */
public class DownLoaderService extends Service {
    private String path;
    private String name;
    private static DownLoaderService loaderService;
    private Downloader downloader;
    private int maxIndex = 0;
    private int currentIndex = 0;
    public static DownLoaderService getInstance() {
        return loaderService;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        loaderService = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        path = intent.getStringExtra("url");
        name = intent.getStringExtra("name");
        downloader = new Downloader(this, path, name + ".mp3");
        downloader.setDownloadListener(downloadListener);
        startDownLoad();

        return super.onStartCommand(intent, flags, startId);
    }

    private void startDownLoad() {
        new DownloaderThread().start();


    }


    public class DownloaderThread extends Thread {
        @Override
        public void run() {
            super.run();
            downloader.start();

        }
    }

    private DownloadListener downloadListener = new DownloadListener() {


        @Override
        public void onStart(int fileByteSize) {
            maxIndex = fileByteSize;
            Intent intent = new Intent();
            intent.setAction(DownLoadAdapter.ACTION_DOWNLOAD_MAX_PROGRESS);
            intent.putExtra("maxIndex", maxIndex);
            sendBroadcast(intent);

        }

        @Override
        public void onPause() {

        }

        @Override
        public void onResume() {

        }

        @Override
        public void onProgress(int receivedBytes) {
            currentIndex = receivedBytes;
            Intent intent = new Intent();
            intent.setAction(DownLoadAdapter.ACTION_DOWNLOAD_CURRENT_PROGRESS);
            intent.putExtra("current", currentIndex);
            sendBroadcast(intent);


        }

        @Override
        public void onFail() {

        }

        @Override
        public void onSuccess(File file) {

        }

        @Override
        public void onCancel() {

        }
    };
}
